package handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;

/**
 * @author zy.jordan
 */
public class FirstServerHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    System.out.println(Calendar.getInstance() + ": 服务端读到消息 -> " + buf.toString(Charset.defaultCharset()));

    // 回复数据到客户端
    System.out.println("服务端写出数据");
    ByteBuf out = getByteBuf(ctx);
    ctx.channel().writeAndFlush(out);
  }

  private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
    byte[] bytes = "你好，Jordan".getBytes(StandardCharsets.UTF_8);
    ByteBuf buf = ctx.alloc().buffer();
    buf.writeBytes(bytes);
    return buf;
  }
}
